package cat.joronya.supermanager.privateleague;

import java.text.NumberFormat;
import java.util.Locale;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.team.Team;

public class PrivateLeagueActivity extends ListActivity
{
	// pel Log
	private static final String TAG = "supermanager";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.PrivateLeagueTeam._ID, 			// 0
            Supermanager.PrivateLeagueTeam.NAME, 			// 1
            Supermanager.PrivateLeagueTeam.MANAGER, 		// 2
            Supermanager.PrivateLeagueTeam.CITY, 			// 3
            Supermanager.PrivateLeagueTeam.POINTS, 			// 4
            Supermanager.PrivateLeagueTeam.GENERAL,			// 5
            Supermanager.PrivateLeagueTeam.BROKER, 			// 6
            Supermanager.PrivateLeagueTeam.MODIFIED_DATE 	// 7
    };
    
    // Gesture detection
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    
    private String league = "undefined";
    private long id = 0;
    private String jornada = "undefined";
    private int selectedPosition = R.id.jornada;
    private Cursor cursor = null;
    private Cursor daysCursor = null;
    
    private NumberFormat decform = null;
    private NumberFormat intform = null;
    
    // share purposes variables
    private Team myTeam;
    
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.private_league);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeagueTeam.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeagueTeam.CONTENT_URI);
        }
        
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
        
        // inicialitzem el detector de gestures
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
        
        // registrem el gesture listener a les vistes del layout
        registerTouchListener();
        
        // guardem id, aixi el tenim quan reordenem el cursor
        id = intent.getLongExtra("cat.joronya.supermanager.privateleague.id",0);

        // recuperem el nom de la lliga i la jornada
        daysCursor = getDaysOfLeague(id);
        if( daysCursor.moveToLast() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		}
        
        // inicialment mostrem ordenat per points
        showTeamsJornada();
    }
	
	public void getMyTeamInPrivateLeague()
	{
        // load manager name
        SharedPreferences settings = 
			PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
   		String manager = settings.getString(Supermanager.PREFS_USERNAME, null);
        
   		String orderClause;
   		switch(selectedPosition)
   		{
   			default:
   			case R.id.jornada:
   				orderClause = Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER;
   				break;
   			case R.id.general:
   				orderClause = Supermanager.PrivateLeagueTeam.GENERAL_SORT_ORDER;
   				break;
   			case R.id.broker:
   				orderClause = Supermanager.PrivateLeagueTeam.BROKER_SORT_ORDER;
   				break;
   		}
   		
		Cursor plCursor = getContentResolver().query(Supermanager.PrivateLeagueTeam.CONTENT_URI, 
				PROJECTION, 
	       		Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		Supermanager.PrivateLeagueTeam.DAY+" = ? ",
	       		new String[]{Long.toString(this.id),jornada},
	            orderClause);
		
		while( plCursor.moveToNext() )
		{
			String tm = plCursor.getString(2).trim();
			
			if( manager.equals(tm) )
			{
				myTeam = new Team();
				myTeam.setPositionOnLeague(plCursor.getPosition()+1);
				myTeam.setName(plCursor.getString(1));
				myTeam.setManager(tm);
				myTeam.setPoints(plCursor.getFloat(4));
				myTeam.setGeneral(plCursor.getFloat(5));
				myTeam.setBroker(plCursor.getInt(6));
			}
		}
		
		plCursor.close();
	}
	
	
	@Override
	protected void onDestroy() 
	{
		daysCursor.close();
		stopManagingCursor(cursor);
		super.onDestroy();
	}

	private void registerTouchListener()
	{
        View listView = findViewById(android.R.id.list);
        listView.setOnTouchListener(gestureListener);
	}
	
	/**
	 * Retorna el cursor amb el llistat de jornades disponibles a l'historic
	 * de la lliga.
	 * @param id
	 * @return
	 */
	private Cursor getDaysOfLeague(long id)
	{
		 // recuperem el nom de la lliga i la jornada
        PrivateLeagueTeamProvider plTeamProvider = new PrivateLeagueTeamProvider();
        Cursor cursor = plTeamProvider.getPrivateLeagueDays(this, id);
        
        return cursor;
	}
	
	/**
	 * Select next day. And call show active classificacion.
	 */
	private void selectNextDay()
	{
		if( daysCursor.moveToNext() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(PrivateLeagueActivity.this, 
        			getResources().getString(R.string.private_league_activity_next_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Select previous day.
	 */
	private void selectPreviousDay()
	{
		if( daysCursor.moveToPrevious() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(PrivateLeagueActivity.this, 
        			getResources().getString(R.string.private_league_activity_previous_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}

	@Override
    public boolean onTouchEvent(MotionEvent event) 
	{
        if (gestureDetector.onTouchEvent(event))
	        return true;
	    else
	    	return false;
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.private_league, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.jornada:
        		showTeamsJornada();
        		return true;
        	case R.id.general:
        		showTeamsGeneral();
        		return true;
        	case R.id.broker:
        		showTeamsBroker();
        		return true;
			case R.id.share:
				// prepare data to share
				getMyTeamInPrivateLeague();
				
				int text;
				switch(selectedPosition)
		   		{
		   			default:
		   			case R.id.jornada:
		   				text = R.string.private_league_share_text_day;
		   				break;
		   			case R.id.general:
		   				text = R.string.private_league_share_text_general;
		   				break;
		   			case R.id.broker:
		   				text = R.string.private_league_share_text_broker;
		   				break;
		   		}
				
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT, 
					getString(text,	myTeam.getName(), myTeam.getPositionOnLeague(), league));
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, getString(R.string.private_league_share_title)));
				return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    class PrivateLeagueAdapter extends CursorAdapter 
	{
    	private int type;
    	
		public PrivateLeagueAdapter(Context theContext, Cursor theCursor, int theType) 
		{
			super(theContext, theCursor);
			this.type = theType;
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			String name = cursor.getString(1);
			String manager = cursor.getString(2);
			String points = decform.format(cursor.getFloat(4));
			String general = decform.format(cursor.getFloat(5));
			String broker = intform.format(cursor.getInt(6));
			
			TextView nameView = (TextView)view.findViewById(R.id.team);
			nameView.setText(name);
			TextView managerView = (TextView)view.findViewById(R.id.manager);
			managerView.setText(manager);
			TextView numView = (TextView)view.findViewById(R.id.points);
			switch(type)
			{
				default:
				case R.id.jornada:
					numView.setText(points);
					break;
				case R.id.general:
					numView.setText(general);
					break;
				case R.id.broker:
					numView.setText(broker);
					break;
			}
			
			TextView positionView = (TextView)view.findViewById(R.id.position);
			positionView.setText((cursor.getPosition()+1)+"º");
			positionView.bringToFront();
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			RelativeLayout row = (RelativeLayout)inflater.inflate(R.layout.private_league_row, parent, false);
			
			// bind data to the row view
			bindView(row, context, cursor);	

			return row;
		}
	}
    
	private void showTeamsJornada()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.jornada;

		// canviem el titular del header "Lliga: Supervermut - Jornada 29"
        TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "Jornada "+jornada));

		// tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
       		Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER);
        
		startManagingCursor(cursor);

		// adapter
		PrivateLeagueAdapter adapter = new PrivateLeagueAdapter(this, cursor, 
				R.id.jornada);
        setListAdapter(adapter);
	}
	
	private void showTeamsGeneral()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.general;

		// canviem el titular del header "Lliga: Supervermut - General"
        TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "General"));
		
		if( cursor != null )
			stopManagingCursor(cursor);
		
		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
				Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
	       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.GENERAL_SORT_ORDER);
        
		startManagingCursor(cursor);
		
		// adapter
		PrivateLeagueAdapter adapter = new PrivateLeagueAdapter(this, cursor,
				R.id.general);
        setListAdapter(adapter);
	}
	
	private void showTeamsBroker()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.broker;

        // canviem el titular del header "Lliga: Supervermut - BrokerBasket"
		TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "BrokerBasket"));

		if( cursor != null )
			stopManagingCursor(cursor);
		
		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
				Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
	       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.BROKER_SORT_ORDER);
        
		startManagingCursor(cursor);
		
		// adapter
		PrivateLeagueAdapter adapter = new PrivateLeagueAdapter(this, cursor,
				R.id.broker);
        setListAdapter(adapter);
	}
	
	/**
	 * Gesture listener to tap left/right and move next/previous day results.
	 * @author pol
	 */
	class MyGestureDetector extends SimpleOnGestureListener 
	{
		private static final int SWIPE_MIN_DISTANCE = 120;
	    private static final int SWIPE_MAX_OFF_PATH = 250;
	    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
        {
            try 
            {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Left Swipe - nextDay");
                	selectNextDay();
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Right Swipe - previousDay");
                    selectPreviousDay();
                }
                else
                {
                    Log.d(TAG,"else Swipe - no change");
                }
            } 
            catch (Exception e)
            {
                // nothing
            }
            return false;
        }

    }
}
